package com.exartisan.thanhdoanhn;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.LayoutParams;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.exartisan.bean.Quiz;
import com.exartisan.datamanager.SurveyManager;
import com.exartisan.datamanager.UserAnswerDataHolder;
import com.exartisan.network.NetworkUtility;
import com.exartisan.network.NewParamBuilder;
import com.exartisan.network.NewResponseTranslater;
import com.exartisan.network.NewRestConnector;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.image.SmartImageView;

/**
 * The Class ExamActivity.
 */
public class ExamActivity extends Activity implements OnCheckedChangeListener{
//	,		OnGestureListener {

	/** The tv question1st. */
	private TextView tvQuestion1st;

	/** The iv illutration1st. */
	private SmartImageView ivIllutration1st;

	/** The rdg answers1st. */
	private RadioGroup rdgAnswers1st;

	/** The tv question2nd. */
	private TextView tvQuestion2nd;

	/** The iv illutration2nd. */
	private SmartImageView ivIllutration2nd;

	/** The rdg answers2nd. */
	private RadioGroup rdgAnswers2nd;

	/** The view switcher. */
	private ViewSwitcher viewSwitcher;

	/** The m current quiz number. */
	private int mCurrentQuizNumber;

	/** The num_quizs. */
	private int num_quizs;

	/** The submited. */
	private boolean submited;

	/** The user answers. */
	private int[] userAnswers;

	/** The is visible page. */
	private boolean isVisiblePage;

	/** The gesture. */
//	private GestureDetector gesture = null;

	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private Button btnStop;

	private EditText edtEssay1;
	private EditText edtEssay2;
	
	private SurveyManager surveyManager;
	private String surveyID;
	
	private ArrayList<String> userTexts;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.studyapp.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_exam);

		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
		tvQuestion1st = (TextView) findViewById(R.id.tvQuestion1st);
		tvQuestion2nd = (TextView) findViewById(R.id.tvQuestion2nd);
		ivIllutration1st = (SmartImageView) findViewById(R.id.ivIllustration1st);
		ivIllutration2nd = (SmartImageView) findViewById(R.id.ivIllustration2nd);
		rdgAnswers1st = (RadioGroup) findViewById(R.id.rdgAnswers1st);
		rdgAnswers2nd = (RadioGroup) findViewById(R.id.rdgAnswers2nd);
		rdgAnswers1st.setOnCheckedChangeListener(this);
		rdgAnswers2nd.setOnCheckedChangeListener(this);
		edtEssay1 = (EditText) findViewById(R.id.edt_essay1);
		edtEssay2 = (EditText) findViewById(R.id.edt_essay2);

		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		btnStop = (Button) findViewById(R.id.btnStop);
		
		surveyManager = SurveyManager.getInstance();
//		surveyManager.addSurveyFromAssets(getApplicationContext(), "phan1.xml");
//		surveyID = "phan1.xml";
		
		String questionData = getIntent().getExtras().getString("question");
//		Toast.makeText(getApplicationContext(), questionData, Toast.LENGTH_LONG).show();
		Log.d("questionData", questionData);
		surveyID = getIntent().getExtras().getString("surveyID");
		ArrayList<Quiz> surveyContent = NewResponseTranslater.getQuestion(questionData);
		surveyManager.addSurvey(surveyID, surveyContent);

		mCurrentQuizNumber = 1;
		num_quizs = surveyManager.getsurveyContent(surveyID).size();
		submited = false;
		isVisiblePage = true;
//		gesture = new GestureDetector(getApplicationContext(), this);
		
		userTexts = new ArrayList<String>();
		for (int i = 0; i < num_quizs; i++) {
			userTexts.add("");
		}
		
		userAnswers = new int[num_quizs];
		for (int i = 0; i < userAnswers.length; i++) {
			userAnswers[i] = -1;
		}
		showQuiz(mCurrentQuizNumber, tvQuestion1st, ivIllutration1st,
				rdgAnswers1st, edtEssay1);

		btnNext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				navigateQuiz(true);
			}
		});

		btnPrevious.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				navigateQuiz(false);
			}
		});

		btnStop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				stopExaming();
			}
		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.studyapp.BaseActivity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		if (checkedId != -1)
			userAnswers[mCurrentQuizNumber - 1] = checkedId;

	}

	/**
	 * Show quiz.
	 * 
	 * @param CurrentQuizNumber
	 *            the current quiz number
	 * @param tvQuestion
	 *            the tv question
	 * @param imageView
	 *            the image view
	 * @param rdgAnswers
	 *            the rdg answers
	 */
	private void showQuiz(final int CurrentQuizNumber, TextView tvQuestion,
			SmartImageView imageView, RadioGroup rdgAnswers, final EditText edtEssay) {

		// String qHead = String.valueOf(CurrentQuizNumber);
		if (CurrentQuizNumber <= num_quizs && CurrentQuizNumber >= 1) {
			if(CurrentQuizNumber==num_quizs){
				btnNext.setVisibility(View.GONE);
			}
			else{
				btnNext.setVisibility(View.VISIBLE);
			}
			int type = surveyManager.getsurveyContent(surveyID).get(CurrentQuizNumber-1).getType();
			String context = "";
			
			if (type == 1) {
				context = "I. TRẮC NGHIỆM";
				rdgAnswers.setVisibility(View.VISIBLE);
				edtEssay.setVisibility(View.GONE);

				char ansPrefix = 'A';
				String question = "<h4>" + context + "<br/>Câu hỏi "
						+ CurrentQuizNumber + ": </h4>" + surveyManager.getsurveyContent(surveyID).get(CurrentQuizNumber-1).getQuestion();
				tvQuestion.setText(Html.fromHtml(question));
				// if (imgUrl.equals("\"\"")) {
				// imageView.setVisibility(View.GONE);
				// } else {
				// imageView.setVisibility(View.VISIBLE);
				// imageView.setImageUrl(data.getContent()
				// .get(CurrentQuizNumber - 1).getImageUrl());
				// }
				// imageView.setImageUrl(data.getContent()
				// .get(CurrentQuizNumber - 1).getImageUrl());
				rdgAnswers.removeAllViews();

				for (int i = 0; i < surveyManager.getsurveyContent(surveyID).get(CurrentQuizNumber-1).getAnswers().size() ; i++) {
					if (i > 0)
						ansPrefix++;
					RadioButton radioButton = new RadioButton(this);
					RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
					params.height = LayoutParams.WRAP_CONTENT;
					params.width = LayoutParams.WRAP_CONTENT;
					params.topMargin = 10;
					radioButton.setLayoutParams(params);
					radioButton
							.setButtonDrawable(R.drawable.btn_radio_holo_light);
					radioButton.setId(i);
					radioButton.setText(ansPrefix + ". " + surveyManager.getsurveyContent(surveyID).get(CurrentQuizNumber-1).getAnswers().get(i).getContent());
					radioButton.setTextColor(Color.BLACK);
					radioButton.setTextSize(16);
					rdgAnswers.addView(radioButton);
					rdgAnswers.clearCheck();
					rdgAnswers.check(userAnswers[CurrentQuizNumber - 1]);
					if (submited)
						radioButton.setEnabled(false);
				}

			} else if (type == 3) {

				context = "II. TỰ LUẬN";
				rdgAnswers.setVisibility(View.GONE);
				edtEssay.setVisibility(View.VISIBLE);

				String question = "<h4>" + context + "<br/>Câu hỏi "
						+ CurrentQuizNumber + ": </h4>" + surveyManager.getsurveyContent(surveyID).get(CurrentQuizNumber-1).getQuestion();
				tvQuestion.setText(Html.fromHtml(question));
				
				edtEssay.addTextChangedListener(new TextWatcher() {
					
					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void afterTextChanged(Editable s) {
						userTexts.set(CurrentQuizNumber - 1, edtEssay.getText().toString());
					}
				});
				
				if (submited)
					edtEssay.setEnabled(false);
				
			}

		}

	}

	/**
	 * Navigate quiz.
	 * 
	 * @param isNext
	 *            the is next
	 */
	private void navigateQuiz(boolean isNext) {
		if ((isNext && mCurrentQuizNumber == num_quizs)
				|| (!isNext && mCurrentQuizNumber == 1))
			return;
		if (isNext) {
			if (mCurrentQuizNumber == num_quizs)
				mCurrentQuizNumber = 1;
			else
				mCurrentQuizNumber++;
		} else {
			if (mCurrentQuizNumber == 1)
				mCurrentQuizNumber = num_quizs;
			else
				mCurrentQuizNumber--;
		}

		if (isVisiblePage) {
			showQuiz(mCurrentQuizNumber, tvQuestion2nd, ivIllutration2nd,
					rdgAnswers2nd, edtEssay2);
			isVisiblePage = false;
		} else {
			showQuiz(mCurrentQuizNumber, tvQuestion1st, ivIllutration1st,
					rdgAnswers1st, edtEssay1);
			isVisiblePage = true;
		}

		if (isNext) {
			viewSwitcher.setInAnimation(this, R.anim.in_animation1);
			viewSwitcher.setOutAnimation(this, R.anim.out_animation1);
			viewSwitcher.showNext();
		} else {
			viewSwitcher.setInAnimation(this, R.anim.in_animation);
			viewSwitcher.setOutAnimation(this, R.anim.out_animation);
			viewSwitcher.showPrevious();
		}
	}

	/**
	 * On click next.
	 * 
	 * @param view
	 *            the view
	 */
	public void onClickNext(View view) {
		navigateQuiz(true);
	}

	/**
	 * On click previous.
	 * 
	 * @param view
	 *            the view
	 */
	public void onClickPrevious(View view) {
		navigateQuiz(false);
	}

	/**
	 * Invalidate quiz.
	 */
	private void invalidateQuiz() {
		if (isVisiblePage) {
			showQuiz(mCurrentQuizNumber, tvQuestion1st, ivIllutration1st,
					rdgAnswers1st, edtEssay1);
		} else {
			showQuiz(mCurrentQuizNumber, tvQuestion2nd, ivIllutration2nd,
					rdgAnswers2nd, edtEssay2);
		}
	}

	/**
	 * Stop examing.
	 */
	private void stopExaming() {
//		submited = true;
//		invalidateQuiz();
		String message = "";
		if (isAllDone()) message = "Bạn có muốn kết thúc bài thi? Khi xác nhận, bài thi của bạn sẽ được gửi về hệ thống!";
		else message = "Bạn chưa hoàn thành bài thi! Bạn có thực sự muốn kết thúc bài thi không? Khi xác nhận, bài thi của bạn sẽ được gửi về hệ thống!";
		showConfirmDialog(message);
	}
	
	@Override
		public void onBackPressed() {
		AlertDialog.Builder restartAlertBuilder = new AlertDialog.Builder(this);
		restartAlertBuilder.setTitle("Cảnh báo");
		restartAlertBuilder
				.setMessage("Bạn có thực sự muốn thoát chương trình làm bài thi không?");
		restartAlertBuilder.setCancelable(false);
		restartAlertBuilder.setPositiveButton("Xác nhận", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				submited = true;
				invalidateQuiz();
				ExamActivity.super.onBackPressed();
			}});
		

		restartAlertBuilder.setNegativeButton("Không", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				
			}
		});
		
	AlertDialog restartAlertDialog = restartAlertBuilder.create();
		restartAlertDialog.show();
		
			
		}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#dispatchTouchEvent(android.view.MotionEvent)
	 */
//	@Override
//	public boolean dispatchTouchEvent(MotionEvent ev) {
//		super.dispatchTouchEvent(ev);
//		return gesture.onTouchEvent(ev);
//	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
	 */
//	@Override
//	public boolean onTouchEvent(MotionEvent event) {
//		return gesture.onTouchEvent(event);
//	}

	/**
	 * On down.
	 * 
	 * @param e
	 *            the e
	 * @return true, if successful
	 */
//	@Override
//	public boolean onDown(MotionEvent e) {
//
//		return false;
//	}

	/** The swipe min velocity. */
	int SWIPE_MIN_VELOCITY = 50;

	/** The swipe min distance. */
	int SWIPE_MIN_DISTANCE = 50;

	/**
	 * On fling.
	 * 
	 * @param e1
	 *            the e1
	 * @param e2
	 *            the e2
	 * @param velocityX
	 *            the velocity x
	 * @param velocityY
	 *            the velocity y
	 * @return true, if successful
	 */
//	@Override
//	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
//			float velocityY) {
//
//		Log.d("Switch", "onFling");
//
//		// Get Position
//		float ev1X = e1.getX();
//		float ev2X = e2.getX();
//
//		// Get distance of X (e1) to X (e2)
//		final float xdistance = Math.abs(ev1X - ev2X);
//		// Get veclocity of cusor
//		// Vận tốc = số điểm ảnh (px) / giây
//		final float xvelocity = Math.abs(velocityX);
//
//		// Vận tốc chuyển đổi X > 100 và khoảng cách từ điểm kéo đầu đến điểm
//		// kéo cuối > 100
//		if ((xvelocity > SWIPE_MIN_VELOCITY)
//				&& (xdistance > SWIPE_MIN_DISTANCE)) {
//			if (ev1X > ev2X)// Switch Left
//			{
//				Log.d("Switch", "Right");
//				navigateQuiz(true);
//			} else// Switch Right
//			{
//				Log.d("Switch", "Left");
//				navigateQuiz(false);
//			}
//		}
//		return false;
//	}

	/**
	 * On long press.
	 * 
	 * @param e
	 *            the e
	 */
//	@Override
//	public void onLongPress(MotionEvent e) {
//
//	}

	/**
	 * On scroll.
	 * 
	 * @param e1
	 *            the e1
	 * @param e2
	 *            the e2
	 * @param distanceX
	 *            the distance x
	 * @param distanceY
	 *            the distance y
	 * @return true, if successful
	 */
//	@Override
//	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
//			float distanceY) {
//
//		return false;
//	}

	/**
	 * On show press.
	 * 
	 * @param e
	 *            the e
	 */
//	@Override
//	public void onShowPress(MotionEvent e) {
//
//	}

	/**
	 * On single tap up.
	 * 
	 * @param e
	 *            the e
	 * @return true, if successful
	 */
//	@Override
//	public boolean onSingleTapUp(MotionEvent e) {
//
//		return false;
//	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onNewIntent(android.content.Intent)
	 */
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onBackPressed()
	 */

	/**
	 * Show confirm dialog.
	 */
	private void showConfirmDialog(String messgae) {
		AlertDialog.Builder restartAlertBuilder = new AlertDialog.Builder(this);
		restartAlertBuilder.setTitle("Thông báo");
		restartAlertBuilder
				.setMessage(messgae);
		restartAlertBuilder.setCancelable(false);
		restartAlertBuilder.setPositiveButton("Xác nhận", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				submited = true;
				invalidateQuiz();
				
				ArrayList<UserAnswerDataHolder> userAnswerData = new ArrayList<UserAnswerDataHolder>();
				for (int i = 0; i < num_quizs; i++) {
					String questionID = ""+surveyManager.getsurveyContent(surveyID).get(i).getQuestionID();
					String answerID = ""+userAnswers[i];
					String answerType = ""+surveyManager.getsurveyContent(surveyID).get(i).getType();
					String answerText = userTexts.get(i);
					Log.d("TextAnswer", answerText);
					String status = "1";
					UserAnswerDataHolder anAnswer = new UserAnswerDataHolder(questionID, answerID, answerType, answerText, status);
					userAnswerData.add(anAnswer);
				}
				
				final ProgressDialog pgdialog = ProgressDialog.show(ExamActivity.this, "", "Đang gửi bài...");
				
				if (NetworkUtility.checkNetworkState(getApplicationContext())) {
			    	
					NewRestConnector.post("", NewParamBuilder
							.BuildParams(NewParamBuilder.BuildSubmit("1", surveyID, userAnswerData)),
							new AsyncHttpResponseHandler() {
								@Override
								public void onSuccess(int arg0, String response) {
									if (response == null){
										pgdialog.dismiss();
										Toast.makeText(getApplicationContext(), "Lỗi",
												Toast.LENGTH_SHORT).show();
								    	return;
									}
									super.onSuccess(arg0, response);
									if (NewResponseTranslater.checkSuccess(response)) {
										Toast.makeText(getApplicationContext(), "Bài thi đã được gửi đi!",
												Toast.LENGTH_SHORT).show();
										finish();
									} else {
										pgdialog.dismiss();
										Toast.makeText(getApplicationContext(), "Gửi thất bại",
												Toast.LENGTH_SHORT).show();
									}

								}

								@Override
								public void onFailure(Throwable arg0, String arg1) {
									super.onFailure(arg0, arg1);
									pgdialog.dismiss();
									Toast.makeText(getApplicationContext(), "Gửi thất bại, vui lòng thử lại",
											Toast.LENGTH_SHORT).show();
								}
							});
				} else {
					pgdialog.dismiss();
					Toast.makeText(getApplicationContext(), "Không có kết nối",
							Toast.LENGTH_SHORT).show();
				}
				
				
				
			}
		});
		restartAlertBuilder.setNegativeButton("Không", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		AlertDialog restartAlertDialog = restartAlertBuilder.create();
		restartAlertDialog.show();

	}

	// /**
	// * Show check mark dialog.
	// */
	// private void showCheckMarkDialog() {
	// int unAnsweredCount = 0;
	// for (int ans : userAnswers) {
	// if (ans == -1)
	// unAnsweredCount++;
	// }
	// String msg;
	// if (unAnsweredCount > 0)
	// msg = new String(
	// "You still have "
	// + unAnsweredCount
	// +
	// " uncheck question, are you sure you want to finish the exam and check mark ?");
	// else
	// msg =
	// "This will stop the exam and process to check mark, are you sure ?";
	// AlertDialog.Builder restartAlertBuilder = new AlertDialog.Builder(this);
	// restartAlertBuilder.setTitle("Warning");
	// restartAlertBuilder.setMessage(msg);
	// restartAlertBuilder.setCancelable(false);
	// restartAlertBuilder.setPositiveButton("Yes", new OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// stopExaming();
	// startCheckResult();
	// }
	// });
	// restartAlertBuilder.setNegativeButton("No", new OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// dialog.cancel();
	// }
	// });
	//
	// AlertDialog restartAlertDialog = restartAlertBuilder.create();
	// restartAlertDialog.show();
	//
	// }

	public String toWord(int answer_id) {
		switch (answer_id) {
		case 0:
			return "A";
		case 1:
			return "B";
		case 2:
			return "C";
		case 3:
			return "D";
		case 4:
			return "E";
		case 5:
			return "F";
		case 6:
			return "G";
		case 7:
			return "H";
		case 8:
			return "I";
		case 9:
			return "J";
		case 10:
			return "K";
		default:
			return "";
		}
	}
	
	private boolean isAllDone(){
		for (int i = 0; i < userAnswers.length; i++) {
			if(userAnswers[i]==-1) return false;
		}
		for (int i = 0; i < userTexts.size(); i++) {
			if(userTexts.get(i).length()<1) return false;
		}
		return true;
	}

}
